package com.bear.atlassianmcp.confluence.mcp.tools;

import com.bear.atlassianmcp.confluence.model.ConfluenceComment;
import com.bear.atlassianmcp.confluence.service.ConfluenceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Confluence评论管理MCP工具
 * 提供评论添加、查询等功能
 */
@Service
public class ConfluenceCommentTools {

    private static final Logger logger = LoggerFactory.getLogger(ConfluenceCommentTools.class);

    private final ConfluenceService confluenceService;

    @Autowired
    public ConfluenceCommentTools(ConfluenceService confluenceService) {
        this.confluenceService = confluenceService;
    }

    /**
     * 添加页面评论
     * 
     * @param pageId 页面ID
     * @param comment 评论内容（支持HTML格式）
     * @return 添加评论结果的格式化文本
     */
    // @Tool(description = "为指定的Confluence页面添加评论")
    public String addComment(String pageId, String comment, ToolContext toolContext) {
        logger.info("MCP Tool: Adding comment to Confluence page {}", pageId);
        
        try {
            ConfluenceComment commentObj = confluenceService.addComment(pageId, comment, toolContext);
            
            StringBuilder result = new StringBuilder();
            result.append("✅ 评论添加成功！\n\n");
            result.append(commentObj.toFormattedString());
            
            logger.info("Successfully added comment to Confluence page {} via MCP", pageId);
            return result.toString();
            
        } catch (Exception e) {
            logger.error("Failed to add comment to Confluence page {} via MCP: {}", pageId, e.getMessage());
            return "❌ 添加评论失败。原因：" + e.getMessage() + 
                   "\n💡 请检查页面ID是否正确，以及是否有添加评论的权限。";
        }
    }

    /**
     * 获取页面评论列表
     * 
     * @param pageId 页面ID
     * @return 页面评论列表的格式化文本
     */
    // @Tool(description = "获取指定Confluence页面的所有评论列表")
    public String getPageComments(String pageId, ToolContext toolContext) {
        logger.info("MCP Tool: Getting comments for Confluence page {}", pageId);
        
        try {
            List<ConfluenceComment> comments = confluenceService.getPageComments(pageId, null, toolContext);
            
            if (comments.isEmpty()) {
                return String.format("💬 页面 %s 当前没有评论。", pageId);
            }
            
            StringBuilder result = new StringBuilder();
            result.append(String.format("💬 页面 %s 的评论列表 (共%d条)：\n\n", pageId, comments.size()));
            
            for (int i = 0; i < comments.size(); i++) {
                ConfluenceComment comment = comments.get(i);
                result.append(String.format("%d. ", i + 1));
                result.append(comment.toFormattedString());
                result.append("\n");
            }
            
            logger.info("Successfully retrieved {} comments for page {} via MCP", comments.size(), pageId);
            return result.toString();
            
        } catch (Exception e) {
            logger.error("Failed to get comments for page {} via MCP: {}", pageId, e.getMessage());
            return "❌ 获取页面评论失败。原因：" + e.getMessage();
        }
    }

    /**
     * 获取页面评论统计
     * 
     * @param pageId 页面ID
     * @return 页面评论统计信息
     */
    // @Tool(description = "获取指定Confluence页面的评论统计信息")
    public String getPageCommentStatistics(String pageId, ToolContext toolContext) {
        logger.info("MCP Tool: Getting comment statistics for Confluence page {}", pageId);
        
        try {
            List<ConfluenceComment> comments = confluenceService.getPageComments(pageId, null, toolContext);
            
            StringBuilder result = new StringBuilder();
            result.append(String.format("📊 页面 %s 的评论统计：\n\n", pageId));
            result.append(String.format("💬 评论总数: %d\n", comments.size()));
            
            if (!comments.isEmpty()) {
                result.append("\n🔍 最近的评论:\n");
                int count = Math.min(3, comments.size());
                for (int i = 0; i < count; i++) {
                    ConfluenceComment comment = comments.get(i);
                    result.append(String.format("• %s", comment.getCreatedBy() != null ? comment.getCreatedBy() : "匿名用户"));
                    if (comment.getCreatedDate() != null) {
                        result.append(String.format(" (%s)", comment.getCreatedDate()));
                    }
                    result.append("\n");
                    
                    String content = comment.getContent();
                    if (content != null && !content.trim().isEmpty()) {
                        String preview = content.length() > 50 ? content.substring(0, 50) + "..." : content;
                        result.append(String.format("  📝 %s\n", preview));
                    }
                }
                
                if (comments.size() > count) {
                    result.append(String.format("... 还有 %d 条评论\n", comments.size() - count));
                }
            }
            
            logger.info("Successfully retrieved comment statistics for page {} via MCP", pageId);
            return result.toString();
            
        } catch (Exception e) {
            logger.error("Failed to get comment statistics for page {} via MCP: {}", pageId, e.getMessage());
            return "❌ 获取评论统计失败。原因：" + e.getMessage();
        }
    }
}
